package com.fagp.mew.cms.permission;

import com.mew.common.entity.back.Log;
import com.fagp.mew.cms.service.ILogService;
import com.fagp.mew.cms.vo.AdminVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    Logger logger = LoggerFactory.getLogger(LoginSuccessHandler.class);

    @Autowired
    private ILogService logService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException,
            ServletException {

        //获得授权后可得到用户信息   可使用SUserService进行数据库操作
        AdminVo userDetails = (AdminVo)authentication.getPrincipal();
        /* Set<SysRole> roles = userDetails.getSysRoles();*/
        String ipAddr = (String) request.getParameter("ip");
        //String ipAddr = IpUtils.getIpAddr(request);
        userDetails.setIp(ipAddr);
        //登录记录
        Log log = Log.builder().name(userDetails.getUsername()).operation(0).ip(ipAddr).thing("登录").state(1).build();
        logService.save(log);

        super.onAuthenticationSuccess(request, response, authentication);
    }
}
